/*
* @Author: Adolphus.Yao
* @Date:   2019-08-28 11:52:42
* @Last Modified by:   Adolphus.Yao
* @Last Modified time: 2019-08-28 18:50:22
*/
package xounter

import (
    "strconv"
    "github.com/kataras/iris"
)

func Configurator(app *iris.Application) {

    app.Get("/xounter", func(ctx iris.Context) {
        ctx.Writef("Counter value = %d", 52)
    })

    users := app.Party("/users", myAuthMiddlewareHandler)
    users.Get("/{id:int}/profile", userProfileHandler)
    users.Get("/messages/{id:int}", userMessageHandler)

    app.Get("/username/{name}", func(ctx iris.Context) {
        ctx.Writef("Hello %s", ctx.Params().Get("name"))
    })

    app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) {
        id, _ := ctx.Params().GetInt("id")
        ctx.Writef("Hello id: %d", id)
    })
    app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx iris.Context) {
        id, _ := ctx.Params().GetInt("id")
        friendid, _ := ctx.Params().GetInt("friendid")
        ctx.Writef("Hello id: %d looking for friend id: ", id, friendid)
    })

    app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) {
        ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level"))
    })

    app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx iris.Context) {
        ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
    })

    app.Get("/upcase/{name:string regexp(^[A-Z]+)}", func(ctx iris.Context) {
        ctx.Writef("name should be only upcase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
    })

    app.Get("/single_file/{myfile:file}", func(ctx iris.Context) {
        ctx.Writef("file type validates if the parameter value has a form of a file name, got: %s", ctx.Params().Get("myfile"))
    })

    app.Get("/myfiles/{directory:path}", func(ctx iris.Context) {
        ctx.Writef("path type accepts any number of path segments, path after /myfiles/ is: %s", ctx.Params().Get("directory"))
    })

    app.Get("/myfiles/xx/{id:int min(1)}", func(ctx iris.Context) {
        id, _ := ctx.Params().GetInt("id")
        ctx.Writef("Hello id: %d", id)
    })
}

func handler(ctx iris.Context){
    ctx.Writef("Hello from method: %s and path: %s", ctx.Method(), ctx.Path())
}

func myAuthMiddlewareHandler(ctx iris.Context){
    id, _ := strconv.Atoi(ctx.Params().Get("id"))
    if 0 < id {
        ctx.Next()//继续执行后续的handler
    } else {
        ctx.WriteString("Authentication failed")
    }
}

func userProfileHandler(ctx iris.Context) {//
    id := ctx.Params().Get("id")
    ctx.WriteString(id)
}

func userMessageHandler(ctx iris.Context){
    id := ctx.Params().Get("id")
    ctx.WriteString(id)
}